package com.bailun91.auth.service.Impl;

import com.bailun91.auth.dto.RoleDto;
import com.bailun91.auth.dto.UserDto;
import com.bailun91.auth.entity.User;
import com.bailun91.auth.mapper.RoleMapper;
import com.bailun91.auth.mapper.UserMapper;
import com.bailun91.auth.service.UserService;
import com.bailun91.auth.util.Constants;
import com.bailun91.auth.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public UserDto findAllUserInfoByUsername(String userName) {

        UserDto userDto = userMapper.findUserPermissionByUsername(userName);
        List<RoleDto> roleDtoList = roleMapper.findRoleListByUserId(userDto.getId());
        userDto.setRoleDtoList(roleDtoList);
        return userDto;

    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public User findById(int id) {
        return userMapper.findById(id);
    }

    /**
     * 查询当前在线用户
     *
     * @return
     */
    @Override
    public List<User> findAllOnlineUser() {

        return null;
    }

    /**
     * 通过userId 踢人
     *
     * @param userId
     */
    @Override
    public void kikoutUserByUserId(Integer userId) {
        User user = userMapper.findById(userId);
        redisTemplate.opsForValue().set(user.getUsername(),"",0, TimeUnit.SECONDS);
    }

    /**
     * 修改密码
     *
     * @param userId
     * @param oldPassword
     * @param newPassword
     */
    @Override
    public boolean ChangePassword(Integer userId, String oldPassword, String newPassword) {

        if (null == userId && null == oldPassword && null == newPassword){
            return false;
        }
        User user = userMapper.findById(userId);
        oldPassword = ShiroUtils.sha256(oldPassword, Constants.SALT);

        if (!oldPassword.equals(user.getPassword())){
            return false;
        }
        newPassword = ShiroUtils.sha256(newPassword,Constants.SALT);
        user.setPassword(newPassword);
        userMapper.insert(user);

        //清除redis中的refreshToken
        redisTemplate.opsForValue().set(user.getUsername(),"",0, TimeUnit.SECONDS);
        return true;
    }
}
